/**
 *    Copyright 2009-2019 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.binding;

import org.apache.ibatis.reflection.ExceptionUtil;
import org.apache.ibatis.session.SqlSession;

import java.io.Serializable;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Map;

/**
 * Dao操作的方法代理类
 *
 * @author Clinton Begin
 * @author Eduardo Macarron
 */
public class MapperProxy<T> implements InvocationHandler, Serializable {

    private static final long serialVersionUID = -6424540398559729838L;
    /**
     * 链接
     */
    private final SqlSession sqlSession;
    /**
     * 对应的映射器类型
     */
    private final Class<T> mapperInterface;
    /**
     * 对于方法的缓存
     */
    private final Map<Method, MapperMethod> methodCache;

    public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
        this.sqlSession = sqlSession;
        this.mapperInterface = mapperInterface;
        this.methodCache = methodCache;
    }

    /**
     * 代理执行方法
     *
     * @param proxy  代理对象
     * @param method 方法
     * @param args   请求参数集合
     * @return 方法执行结果
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        try {
            if (Object.class.equals(method.getDeclaringClass())) {
                // Java Object对象的原生方法
                return method.invoke(this, args);
            } else if (isDefaultMethod(method)) {
                // 属于接口的默认方法
                return invokeDefaultMethod(proxy, method, args);
            }
        } catch (Throwable t) {
            throw ExceptionUtil.unwrapThrowable(t);
        }
        // 对方法进行缓存
        final MapperMethod mapperMethod = cachedMapperMethod(method);
        // 通过参数和会话获取JDBC返回数据
        return mapperMethod.execute(sqlSession, args);
    }

    /**
     * 如果当前方法已被缓存，那么直接返回，否则在添加缓存之后，再返回，
     *
     * @param method 方法
     */
    private MapperMethod cachedMapperMethod(Method method) {
        // 方法缓存
        return methodCache.computeIfAbsent(method, k -> new MapperMethod(mapperInterface, method, sqlSession.getConfiguration()));
    }

    private Object invokeDefaultMethod(Object proxy, Method method, Object[] args)
            throws Throwable {
        final Constructor<MethodHandles.Lookup> constructor = MethodHandles.Lookup.class
                .getDeclaredConstructor(Class.class, int.class);

        if (!constructor.isAccessible()) {
            // 重置可访问性
            constructor.setAccessible(true);
        }
        // 获取方法所属类
        final Class<?> declaringClass = method.getDeclaringClass();
        // 通过反射执行对应类的默认方法
        return constructor
                .newInstance(declaringClass,
                        MethodHandles.Lookup.PRIVATE | MethodHandles.Lookup.PROTECTED
                                | MethodHandles.Lookup.PACKAGE | MethodHandles.Lookup.PUBLIC)
                .unreflectSpecial(method, declaringClass)
                .bindTo(proxy)
                .invokeWithArguments(args);
    }

    /**
     * Backport of java.lang.reflect.Method#isDefault()
     */
    private boolean isDefaultMethod(Method method) {
        // 默认方法是在接口中声明的公共非抽象实例方法
        return (
                method.getModifiers()
                        &
                        (Modifier.ABSTRACT | Modifier.PUBLIC | Modifier.STATIC)
        ) == Modifier.PUBLIC /*非抽象的公共方法*/
                && method.getDeclaringClass().isInterface()/*方法属于接口*/;
    }
}
